<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>志愿讲堂</span>
      </div>
    </template>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="">
        <div class="search">
          <el-input
            v-model="formInline.search"
            style="width: 237px"
            placeholder="关键词..."
            clearable
            @change="searchTable"
          />
          <el-button class="btn" @click="searchTable">搜索</el-button>
        </div>
      </el-form-item>
      <el-form-item class="input">
        <el-select
          v-model="formInline.viewing_permission"
          placeholder="权限"
          clearable
          @change="searchTable"
        >
          <el-option
            v-for="item in limitData"
            :key="item.type"
            :label="item.name"
            :value="item.type"
            :disabled="item.type == 0"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="input">
        <el-select
          v-model="formInline.type"
          placeholder="类型"
          @change="searchTable"
          clearable
        >
          <el-option
            v-for="item in typeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.id == 0"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="input">
        <el-select
          v-model="formInline.status"
          placeholder="状态"
          @change="searchTable"
          clearable
        >
          <el-option
            v-for="item in statusList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.id == 2"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="float: right; margin-right: 0">
        <!--  v-hasPermi="['operation:classRoom:videosClass']" -->
        <el-button
          class="classBg"
          v-hasPermi="['operation:href:editBanner']"
          @click="payBanner"
          >基础配置</el-button
        >
        <el-button
          style="background-color: #fff"
          class="classBg"
          @click="VideoBtn"
          >视频库</el-button
        >
        <el-button class="primary" type="primary" @click="saveCourses"
          >发布课程</el-button
        >
        <!--  v-hasPermi="['operation:classRoom:addClass']" -->
      </el-form-item>
    </el-form>
    <my-table :tableData="tableData" :columns="columns" :loading="true">
      <template #sort="{ row }">
        <el-popover
          placement="bottom"
          :width="200"
          trigger="click"
          :visible="row.visible"
        >
          <div class="content">
            <span>第</span>
            <el-input
              v-model="row.sort"
              class="input"
              style="width: 75px; margin: 0 10px"
              placeholder="n"
            />
            <span>个</span>
            <el-button class="btn" @click="sortBtn(row)">确定</el-button>
          </div>
          <template #reference>
            <div class="sort" @click="visible = true">
              <span class="">{{ row.sort }}</span>
              <ArrowDown class="ArrowDown" />
            </div>
          </template>
        </el-popover>
      </template>
      <template #img="{ row }">
        <!-- <img :src="row.cover" class="coverImg" /> -->
        <ProcessedImage
          params="imageView2/2/w/64/h/64"
          :src="get(row, 'cover', '')"
        />
      </template>
      <template #viewing_permission="{ row }">
        {{
          row.viewing_permission == 1
            ? '免费'
            : row.viewing_permission == 2
              ? 'vip'
              : row.viewing_permission == 3
                ? '收费'
                : '-'
        }}
      </template>
      <template #type="{ row }">
        <span>{{ filterType(row.type) }}</span>
      </template>

      <template #home="{ row }">
        <el-tooltip effect="dark" placement="top">
          <el-switch
            :disabled="row.status == 0 ? true : false"
            v-model="row.home"
            style="margin-right: 5px"
            @change="switchChange('home', row)"
          />
          <template #content v-if="row.status == 0"> 请设置课程状态 </template>
          <template #content v-else>
            {{ row.home ? '已' : '未' }}推荐到首页
          </template>
        </el-tooltip>
        <span class="status">{{ row.home == true ? '推荐' : '不推荐' }} </span>
      </template>

      <template #recommend="{ row }">
        <el-tooltip effect="dark" placement="top">
          <el-switch
            :disabled="
              (row.recommend == 0 && row.banner_img == null) ||
              row.banner_img == '' ||
              row.status == 0
                ? true
                : false
            "
            v-model="row.recommend"
            style="margin-right: 5px"
            @change="switchChange('recommend', row)"
          />
          <template #content v-if="row.status == 0"> 请设置课程状态 </template>
          <template
            #content
            v-else-if="row.banner_img == '' || row.banner_img == null"
          >
            请设置轮播图
          </template>

          <template #content v-else>
            {{ row.recommend ? '已' : '未' }}推荐轮播图
          </template>
        </el-tooltip>
        <span class="status"
          >{{ row.recommend == true ? '推荐' : '不推荐' }}
        </span>
      </template>
      <!--   v-hasPermi="['operation:editClass:editClass']" -->
      <template #schedule="{ row }">
        <div class="num" @click="classRoute(row)">
          <p class="add">+</p>
          <span>{{ classNum(row) ?? 0 }}</span>
        </div>
      </template>
      <template #status="{ row }">
        <!-- v-hasPermi="['operation:editClass:switchClass']" -->
        <div class="switch">
          <el-switch
            style="margin-right: 5px"
            v-model="row.status"
            @change="switchChange('status', row)"
          />
          <span class="status"
            >{{ row.status == true ? '上架' : '下架' }}
          </span>
        </div>
      </template>
      <template #operation="{ row }">
        <div>
          <!--  v-hasPermi="['operation:editClass:editClass']" -->
          <span class="editicon" @click="editInfo(row)"
            ><EditPen style="width: 1em; height: 1em; margin-right: 8px"
          /></span>
          <span class="editicon" @click="detele(row, 1)">
            <!-- v-hasPermi="['operation:classRoom:delteleClass']" -->
            <Delete style="width: 1em; height: 1em; margin-right: 8px"
          /></span>
        </div>
      </template>
    </my-table>
    <Video v-model="drawer">
      <template #center>
        <div class="box">
          <div>
            <div class="search">
              <el-input
                v-model="videoForm.search"
                style="width: 237px"
                placeholder="在视频库中搜索"
                clearable
                @change="searchVideo"
              />
              <el-button class="btn" @click="searchVideo">搜索</el-button>
            </div>
          </div>
          <div class="right">
            <!--  v-hasPermi="['operation:classRoom:Addvideos']" -->
            <el-button class="video" type="primary" @click="saveUploadVideo"
              >上传视频</el-button
            >
          </div>
        </div>
        <div class="drawerTable">
          <my-table :columns="columnDrawer" :tableData="drawerDataList">
            <template #imgs="{ row }">
              <ProcessedImage
                v-if="!row.cover"
                :src="'https://b.gaokaow.cc/no-cover.png'"
                params="imageView2/1/w/100/h/100"
              />
              <ProcessedImage
                v-else
                :src="row.cover"
                params="imageView2/1/w/100/h/100"
              />
            </template>
            <template #operation="{ row }">
              <div>
                <span class="editicon" @click="saveEditInfoVideo(row)"
                  ><EditPen style="width: 1em; height: 1em; margin-right: 8px"
                /></span>
                <span class="editicon" @click="detele(row, 2)"
                  ><Delete style="width: 1em; height: 1em; margin-right: 8px"
                /></span>
              </div>
            </template>
          </my-table>
        </div>
        <div class="pagination">
          <pagination
            :formInline="videoForm"
            @sizeChange="sizeChangeVideo"
            @currentChange="currentChangeVideo"
          ></pagination>
        </div>
      </template>
    </Video>

    <!-- 视频上传弹窗 -->
    <Dialog v-model="dialogFormVisible" title="上传视频">
      <template #center>
        <div class="center">
          <videoList
            ref="fileUploader"
            @progress="progress"
            @updateData="updateData"
          ></videoList>
        </div>
        <p class="info_s">
          建议上传视频：比例16：9，分辨率：1280*720，视频大小不超过2G
        </p>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="startUpload"
            :dialogFormVisible="dialogFormVisible"
          >
            开始上传
          </el-button>
        </div>
      </template>
    </Dialog>

    <Dialog title="修改" v-model="dialogVisible" width="560">
      <template #center>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          class="demo-ruleForm"
          status-icon
          style="margin-top: 30px"
        >
          <el-form-item label="视频标题" prop="name">
            <el-input v-model="ruleForm.name" style="width: 280px" />
          </el-form-item>
          <el-form-item label="视频封面" prop="pic">
            <div class="center img2">
              <ImagUploa
                width="280px"
                :isShowTip="false"
                :isShow="false"
                :limit="1"
                :modelValue="modelValueList"
                @update:modelValue="modelValue"
              ></ImagUploa>
            </div>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveVideoEditBtn"> 确定 </el-button>
        </div>
      </template>
    </Dialog>
    <div class="pagination">
      <pagination
        :formInline="formInline"
        @sizeChange="sizeChange"
        @currentChange="currentChange"
      ></pagination>
    </div>
  </el-card>
</template>
<script setup>
import videoList from '@/components/videoUpload/index.vue';
import { reactive, onMounted, ref } from 'vue';
import Video from './components/video.vue';
import Dialog from './components/Dialog.vue';
import myTable from './components/tableList.vue';
import pagination from './components/pagination.vue';
import ImagUploa from '@/components/ImageUpload2/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import classRoom from '@/modules';
import { get } from 'lodash';
// import bus from '@/utils/bus.js';
const {
  gettableDataApi,
  videoListApi,
  saveApi,
  delVideoApi,
  saveVideoApi,
  delApi,
  classTypeListApi,
} = classRoom;
// 路由
const router = useRouter();
const drawer = ref(false);
const visible = ref(false);
const dialogFormVisible = ref(false);
const dialogVisible = ref(false);
const ruleFormRef = ref(null);
const fileUploader = ref(null);
const drawerDataList = ref([]);
//图片
const modelValueList = ref([]);
const ruleForm = ref({
  name: '',
  pic: '',
  cover: '',
  id: '',
});
const formInline = ref({
  page: 1,
  pageSize: 10,
  search: '',
  viewing_permission: '',
  type: '',
  status: '',
  sort: 0,
  total: null,
});
const tableConfig = ref({
  page: 1,
  pageSize: 10,
  recommend: '',
  home: '',
  status: '',
  sort: 0,
});
const videoForm = ref({
  page: 1,
  pageSize: 10,
  total: null,
  search: '',
});
const params = ref({
  page: 1,
  pageSize: 100,
});

const tableData = ref([]);
const columns = ref([
  { prop: 'sort', label: '排序' },
  { prop: 'img', label: '封面' },
  { prop: 'name', label: '标题' },
  { prop: 'create_time', label: '创建时间' },
  { prop: 'viewing_permission', label: '观看权限' },
  { prop: 'type', label: '课程类别' },
  { prop: 'schedule', label: '课节' },
  { prop: 'home', label: '首页推荐' },
  { prop: 'recommend', label: 'banner推荐' },
  { prop: 'status', label: '课程状态', slot: 'statusSlot' },
  { prop: 'operation', label: '操作' },
]);
// 右侧抽屉数据
const columnDrawer = ref([
  { prop: 'imgs', label: '视频封面' },
  { prop: 'name', label: '视频名称' },
  { prop: 'create_time', label: '上传时间' },
  { prop: 'operation', label: '操作' },
]);

const limitData = [
  { type: 0, name: '权限' },
  { type: 1, name: '免费' },
  { type: 2, name: 'VIP' },
  { type: 3, name: '收费' },
];
const typeList = ref([]);
const statusList = [
  { id: 2, name: '状态' },
  { id: 1, name: '已上架' },
  { id: 0, name: '已下架' },
];
const rules = reactive({
  name: [
    {
      required: true,
      message: '请输入视频标题',
      trigger: 'blur',
    },
  ],
  pic: [
    {
      required: true,
      message: '请选择视频封面',
      trigger: 'blur',
    },
  ],
});

const switchChange = (val, row) => {
  tableConfig.value.recommend = row.recommend ? 1 : 0;
  tableConfig.value.home = row.home ? 1 : 0;
  tableConfig.value.status = row.status ? 1 : 0;
  tableConfig.value.id = row.id;
  tableConfig.value.sort = row.sort;
  sortApi();
};

// 从父组件触发上传的方法
const startUpload = () => {
  if (fileUploader.value) {
    fileUploader.value.triggerUpload(); // 调用子组件中的 triggerUpload 方法
  }
};
const progress = ({ stepNumber }) => {
  if (stepNumber == 100) {
    dialogFormVisible.value = false;
    // tags.value = false;
  }
};
const updateData = () => {
  setTimeout(() => {
    getVideoTableData();
  }, 100);
};
const modelValue = (val) => {
  modelValueList.value = val;
  ruleForm.value.pic = val;
  ruleForm.value.cover = val;
};
const payBanner = () => {
  router.push({ path: '/operation/href' });
};
// 课节数s
const classNum = (row) => {
  if (row) {
    const valuesArray = row.videos.split(',');
    // 使用 filter 方法过滤掉空字符串
    const nonEmptyElements = valuesArray.filter((item) => item !== '');

    // 计算非空元素的长度
    return nonEmptyElements.length;
  }
};
//搜索
const searchTable = () => {
  formInline.value.page = 1;
  getTableData();
};
// 搜索视频
const searchVideo = () => {
  videoForm.value.page = 1;
  getVideoTableData();
};
//排序
const sortApi = async () => {
  const { sort, id, recommend, status, home } = tableConfig.value;
  try {
    const res = await saveApi({ sort, id, recommend, status, home });
    if (res.code == 20000) {
      ElMessage({
        message: res.msg,
        type: 'success',
      });
      getTableData();
    }
  } catch (err) {
    console.log(err);
  }
};
const sortBtn = (row) => {
  tableConfig.value.id = row.id;
  tableConfig.value.sort = row.sort;
  sortApi();
};
// 修改视频封面
const saveVideoEditBtn = async () => {
  await ruleFormRef.value.validate((value) => {
    if (value) {
      saveVideoEditInfo();
    }
  });
};
//视频库编辑
const saveVideoEditInfo = async () => {
  const { id, cover, name } = ruleForm.value;
  const res = await saveVideoApi({ id, cover, name });
  if (res.code == 20000) {
    ElMessage({
      type: 'success',
      message: res.msg,
    });
    getVideoTableData();
    dialogVisible.value = false;
  }
};
const saveEditInfoVideo = (row) => {
  dialogVisible.value = true;
  modelValueList.value = row.cover;
  ruleForm.value.pic = row.cover;
  Object.assign(ruleForm.value, row);
};
//删除列表
const deltableDataRow = async (id) => {
  const res = await delApi({ id });
  if (res.code == 20000) {
    ElMessage({
      type: 'success',
      message: res.msg,
    });
    getTableData();
  }
};
// 删除视频
const delVideo = async (id) => {
  const res = await delVideoApi({ id });
  if (res.code == 20000) {
    ElMessage({
      type: 'success',
      message: res.msg,
    });
    getVideoTableData();
  }
};
const detele = (row, type) => {
  ElMessageBox.confirm('确认要删除吗？', '确认提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      type == 1 ? deltableDataRow(row.id) : delVideo(row.id);
    })
    .catch(() => {});
};
const classRoute = (row) => {
  router.push({
    path: 'editClass',
    query: { id: 2, typeId: row.id },
  });
};

//视频上传value
const saveUploadVideo = () => {
  dialogFormVisible.value = true;
};
const saveCourses = () => {
  router.push({ path: '/operation/editClass' });
};
const editInfo = (row) => {
  router.push({
    path: '/operation/editClass',
    query: { ids: row.id, title: '编辑' },
  });
};
const sizeChange = (val) => {
  formInline.value.pageSize = val;
  getTableData();
};
const currentChange = (val) => {
  formInline.value.page = val;
  getTableData();
};
//
const sizeChangeVideo = (val) => {
  videoForm.value.pageSize = val;
  getVideoTableData();
};
const currentChangeVideo = (val) => {
  videoForm.value.page = val;
  getVideoTableData();
};
//视频库
const VideoBtn = () => {
  drawer.value = true;
  getVideoTableData();
};
//视频仓库列表
const getVideoTableData = async () => {
  const { page, pageSize, search } = videoForm.value;
  try {
    const { data } = await videoListApi({ page, pageSize, search });
    drawerDataList.value = data.data;
    videoForm.value.total = data.total;
  } catch (err) {
    console.log(err);
  }
};
// 课程类别转换
const filterType = (val) => {
  if (val) {
    const names = val.map((id) => {
      const item = typeList.value.find((item) => item.id === id);
      return item ? item.name : null;
    });
    // / 将数组转换成字符串，用 / 分隔
    return names.filter((name) => name !== null).join('/'); // 过滤掉 null 并合并为字符串
  }
};
//获取列表数据
const getTableData = async () => {
  const { data } = await gettableDataApi(formInline.value);
  tableData.value = data.data;
  formInline.value.total = data.total;
  tableData.value.forEach((item) => {
    item.status = item.status === 1 ? true : false;
    item.type = item.type.split(',').map(Number);
    item.recommend = item.recommend === 1 ? true : false;
    item.home = item.home === 1 ? true : false;
  });
};
//课程类别
const getListData = async () => {
  const { data } = await classTypeListApi(params.value);
  typeList.value = data.data;
  typeList.value.unshift({ id: 0, name: '类型' });
};
onMounted(() => {
  getTableData();
  getListData();
  // classType();
});
</script>
<style lang="scss" scoped>
:deep(.el-upload) {
  width: 363px;
}
:deep(.el-upload-list__item .is-success) {
  width: 280px !important;
}
:deep(.el-upload--picture-card) {
  width: 360px;
}
:deep(.el-dialog__header) {
  height: 40px !important;
  min-height: 40px !important;
}
:deep(.el-dialog__footer) {
  justify-content: right;
  padding-top: 10px;
}
:deep(.el-button--primary) {
  background: var(--primary-color);
}
.img2 :deep(.el-upload--picture-card) {
  width: 280px;
}
.input :deep(.el-select__wrapper) {
  width: 180px;
  height: 40px;
}
.search :deep(.el-input) {
  height: 40px;
  border-radius: none !important;
  border: 1px solid var(--primary-color);
}
.search :deep(.el-button) {
  height: 43px !important;
  background: var(--primary-color);
  color: #fff;
  border-radius: none !important;
  width: 86px !important;
}
.box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 24px;
}
.drawerTable {
  margin-top: 20px;
}
#sortbtn {
  margin-left: 10px;
  width: 75px !important;
  height: 32px;
  color: #fff;
  background-color: var(--primary-color);
}
.content {
  display: flex;
  align-items: center;
  cursor: pointer;
}
.btn {
  margin-left: 10px;
  color: #fff;
  background: var(--primary-color);
}
.switch {
  display: flex;
  align-items: center;
  .status {
    display: inline-block;
    margin-left: 5px;
  }
}
.num {
  display: flex;
  align-items: center;
  cursor: pointer;
  .add {
    display: inline-block;
    width: 14px;
    height: 14px;
    line-height: 14px;
    text-align: center;
    border-radius: 50%;
    background: var(--primary-color);
    color: #fff;
    margin-right: 5px;
  }
}
.editicon {
  cursor: pointer;
  font-size: 20px;
  color: #1d2129;
}
.editicon:first-child {
  margin-right: 10px;
}

.box-card {
  margin: 20px;
  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;
  }

  .sort {
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    .ArrowDown {
      width: 1em;
      height: 1em;
      margin-right: 8px;
      margin-left: 5px;
      display: inline-block;
    }
  }
  .search {
    display: inline-block;
    .btn {
      margin-left: -3px;
    }
  }
  .classBg {
    border: 1px solid var(--primary-color);
    color: var(--primary-color);
    height: 40px;
  }
  :deep(.el-button + .el-button) {
    height: 40px;
    background: var(--primary-color);
  }
  .icon {
    display: flex;
    align-items: center;
    cursor: pointer;
    justify-content: center;
  }
  .video {
    height: 42px;
  }
  .right {
    :deep(.el-button--primary) {
      background: var(--primary-color);
    }
  }
  .icon:hover {
    color: var(--primary-color);
  }
  .saveIcon {
    width: 20px;
    height: 20px;
    margin-right: 8px;
    cursor: pointer;
    margin-right: 10px;
  }
  .sortIcon {
    cursor: pointer;
    .ArrowDown {
      display: inline-block;
      width: 15px;
      height: 15px;
      line-height: 15px;
      margin-left: 3px;
    }
  }
  .sortIcon:hover {
    color: var(--primary-color);
  }
  .pagination {
    margin-top: 20px;
  }
}
.center {
  margin: 20px 0;
}
.info_s {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  font-size: 12px;
  color: #4e5969;
}
.coverImg {
  // height: 54px;
  width: 100px;
}
</style>
